package com.lt.base;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.viewbinding.ViewBinding;

import com.hjq.toast.Toaster;
import com.lt.app.ResHelper;
import com.lt.common.DebugHelper;
import com.lt.listener.DataServiceListener;

import java.lang.ref.WeakReference;

public abstract class BaseFragment<A extends BaseActivity, T extends ViewBinding>
        extends androidx.fragment.app.Fragment
        implements DataServiceListener {
    protected final String TAG = this.getClass().getSimpleName();
    protected final int Msg_Base = 10000;
    protected final int msg_req = Msg_Base + 1111;
    protected T binding;
    protected boolean isShow = false;
    /**
     * 是否初始化过
     */
    private boolean mInitialize;
    /**
     * Activity 对象
     */
    private A mActivity;
    /**
     * 根布局
     */
    protected View mRootView;

    /**
     * 获取布局 ID
     */
    protected abstract View getLayoutView();

    /**
     * 初始化数据
     */
    protected abstract void init();

    /**
     * 访问HTTP接口后返回时的回调 </br>
     *
     * @param msg 返回的消息内容
     */
    protected abstract void receiveMessage(Message msg);

    private static class MyHandler extends Handler {
        WeakReference<BaseFragment> mFragment;

        MyHandler(BaseFragment fragment) {
            mFragment = new WeakReference<>(fragment);
        }

        @Override
        public void handleMessage(Message msg) {
            if (mFragment != null) {
                BaseFragment theFragment = mFragment.get();
                if (theFragment != null) {
                    theFragment.handleMessage(msg);
                }
            }
        }
    }

    protected Handler _handler = new MyHandler(this);

    protected void handleMessage(Message message) {
        if (getActivity() == null || getActivity().isFinishing()) {
            return;
        }
        BaseFragment.this.receiveMessage(message);
    }

    @SuppressWarnings("unchecked")
    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        // 获得全局的 Activity
        mActivity = (A) requireActivity();
    }

    @Override
    public void onDetach() {
        _handler.removeCallbacksAndMessages(this);
        BaseApplication.getInstance().getNotificationCenter().removeObserver(this);
        mActivity = null;
        super.onDetach();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }

    @Override
    public void sendMessage(Message message) {
        if (_handler != null) {
            _handler.sendMessage(message);
        }
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mRootView = getLayoutView();
        return mRootView;
    }


    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        init();
    }

    @Override
    public void onResume() {
        super.onResume();
        if (!mInitialize) {
            mInitialize = true;
            initFragment();
        }
        isShow = true;
    }

    @Override
    public void onPause() {
        super.onPause();
        isShow = false;
    }

    protected void initFragment() {

    }

    /**
     * 销毁当前 Fragment 所在的 Activity
     */
    public void finish() {
        if (mActivity != null && !mActivity.isFinishing()) {
            mActivity.finish();
        }
    }

    /**
     * 获取绑定的 Activity，防止出现 getActivity 为空
     */
    public A getAttachActivity() {
        return mActivity;
    }

    protected void log(String str) {
        DebugHelper.e(TAG, str);
    }

    public void showToast(Object o) {
        getAttachActivity().showToast(o);
    }

    public boolean onBackPressed() {
        return false;
    }

    protected void sendNotification(String name) {
        BaseApplication.getInstance().getNotificationCenter().sendNotification(name, null);
    }

    protected void addNotification(String name) {
        addNotification(name, name);
    }

    protected void addNotification(String name, String methodName) {
        BaseApplication.getInstance().getNotificationCenter().removeObserver(this, name);
        BaseApplication.getInstance().getNotificationCenter().addObserver(this, name, methodName);
    }
}
